<script setup>
import { ref, onMounted, computed } from 'vue'
import {
  NButton,
  NForm,
  NFormItem,
  NInput,
  NRadio,
  NRadioGroup,
  NCheckbox,
  NCheckboxGroup,
  NCard,
  NDivider,
  NSpin,
  NEmpty,
  NModal,
  NSelect,
  NTabs,
  NTabPane,
  NTable,
  NTag,
  NPopconfirm
} from 'naive-ui'
import api from '@/api'

const props = defineProps({
  infoData: {
    type: Object,
    required: true
  }
})

const emit = defineEmits(['submit-success', 'update-success', 'close'])

const visible = ref(true)
const loading = ref(false)
const submitting = ref(false)

// 问卷数据
const surveyData = ref({
  id: null,
  name: '',
  info: []
})

const answers = ref([])
const surveyList = ref([])
const currentSurveyIndex = ref(0)

// 问卷答案列表
const surveyAnswers = ref([])
const answersLoading = ref(false)

// 当前模式：'fill' 填写模式
const currentMode = ref('fill')

onMounted(() => {
  loadSurveyList()
  loadSurveyAnswers()
})

// 加载问卷列表
async function loadSurveyList() {
  try {
    loading.value = true
    const response = await api.getSurveys({
      type: '1',
    })
    surveyList.value = response.data || []
    
    if (surveyList.value.length > 0) {
      loadSurvey(0) // 直接使用索引
    }
  } catch (error) {
    console.error('加载问卷列表失败:', error)
    $message.error('加载问卷列表失败')
  } finally {
    loading.value = false
  }
}

// 加载问卷数据
function loadSurvey(surveyIndex) {
  try {
    const survey = surveyList.value[surveyIndex]
    if (!survey) return
    
    surveyData.value = { ...survey }
    
    // 解析问卷内容
    if (surveyData.value.info) {
      try {
        const parsedInfo = JSON.parse(surveyData.value.info)
        let info = []
        
        // 确保info是数组格式
        if (Array.isArray(parsedInfo)) {
          info = parsedInfo
        } else if (parsedInfo && parsedInfo.questions && Array.isArray(parsedInfo.questions)) {
          // 如果是旧格式 {questions: [...]}，提取questions数组
          info = parsedInfo.questions
        } else {
          info = []
        }
        
        // 确保每个项目都有options字段
        surveyData.value.info = info.map(question => ({
          ...question,
          options: question.options || []
        }))
      } catch (error) {
        console.error('解析问卷数据失败:', error)
        surveyData.value.info = []
      }
    }
    
    // 查找该问卷的已有答案
    const existingAnswer = surveyAnswers.value.find(answer => answer.form_id === survey.id)
    
    if (existingAnswer && existingAnswer.info) {
      try {
        const answerInfo = JSON.parse(existingAnswer.info)
        console.log('找到已有答案:', answerInfo)
        
        // 将答案数据转换为填写模式需要的格式
        const formattedAnswers = []
        surveyData.value.info.forEach((question, index) => {
          const answer = answerInfo[index]
          
          if (question.type == 1) {
            // 填空项直接使用文本
            formattedAnswers.push(answer || '')
          } else if (question.type == 2) {
            // 单选项需要找到对应的选项索引
            const optionIndex = question.options.findIndex(option => option.text === answer)
            formattedAnswers.push(optionIndex >= 0 ? optionIndex : '')
          } else if (question.type == 3) {
            // 多选项需要找到对应的选项索引数组
            const optionIndices = []
            if (Array.isArray(answer)) {
              answer.forEach(answerText => {
                const optionIndex = question.options.findIndex(option => option.text === answerText)
                if (optionIndex >= 0) {
                  optionIndices.push(optionIndex)
                }
              })
            }
            formattedAnswers.push(optionIndices)
          }
        })
        
        answers.value = formattedAnswers
        console.log('已填入答案:', answers.value)
      } catch (error) {
        console.error('解析已有答案失败:', error)
        answers.value = new Array(surveyData.value.info.length).fill('')
      }
    } else {
      // 没有已有答案，初始化空答案数组
      answers.value = new Array(surveyData.value.info.length).fill('')
    }
  } catch (error) {
    console.error('加载问卷失败:', error)
    $message.error('加载问卷失败')
  }
}

// 加载问卷答案列表
async function loadSurveyAnswers() {
  try {
    answersLoading.value = true
    const response = await api.getSurveyAnswers({
      user_id: props.infoData.user_id
    })
    surveyAnswers.value = response.data || []
    console.log(surveyAnswers.value)
  } catch (error) {
    console.error('加载问卷答案失败:', error)
    $message.error('加载问卷答案失败')
  } finally {
    answersLoading.value = false
  }
}

// 切换问卷
function switchSurvey(index) {
  currentSurveyIndex.value = index
  loadSurvey(index)
}


// 提交问卷
async function submitSurvey() {
  // 验证必填项
  for (let i = 0; i < surveyData.value.info.length; i++) {
    const question = surveyData.value.info[i]
    if (question.required) {
      if (question.type == 1) {
        // 填空项
        if (!answers.value[i] || !answers.value[i].trim()) {
          $message.error(`${i + 1}项是必填项，请填写答案`)
          return
        }
      } else if (question.type == 2) {
        // 单选项
        if (answers.value[i] === '' || answers.value[i] === null || answers.value[i] === undefined) {
          $message.error(`${i + 1}项是必填项，请选择答案`)
          return
        }
      } else if (question.type == 3) {
        // 多选项
        if (!answers.value[i] || answers.value[i].length === 0) {
          $message.error(`${i + 1}项是必填项，请选择答案`)
          return
        }
      }
    }
  }
  
  try {
    submitting.value = true
    
    // 格式化答案
    const formattedAnswers = []
    surveyData.value.info.forEach((question, index) => {
      if (question.type == 1) {
        // 填空项直接保存文本
        formattedAnswers.push(answers.value[index] || '')
      } else if (question.type == 2) {
        // 单选项保存选项文本
        const selectedIndex = answers.value[index]
        const selectedOption = question.options[selectedIndex]
        formattedAnswers.push(selectedOption ? selectedOption.text : '')
      } else if (question.type == 3) {
        // 多选项保存选项文本数组
        const selectedIndices = answers.value[index] || []
        const selectedOptions = selectedIndices.map(idx => question.options[idx]?.text).filter(Boolean)
        formattedAnswers.push(selectedOptions)
      }
    })
    
    // 提交答案
    await api.submitSurveyAnswer({
      form_id: surveyData.value.id,
      user_id: props.infoData.id,
      info: formattedAnswers
    })
    
    $message.success('问卷提交成功！')
    
    // 刷新答案列表
    loadSurveyAnswers()
    
    // 触发父组件事件
    emit('submit-success', {
      formId: surveyData.value.id,
      info: formattedAnswers
    })
    
    // 提交成功后关闭窗口
    closeModal()
    
  } catch (error) {
    console.error('提交问卷失败:', error)
    $message.error('提交问卷失败')
  } finally {
    submitting.value = false
  }
}


// 获取项目类型文本
function getQuestionTypeText(type) {
  const typeMap = {
    1: '填空项',
    2: '单选项',
    3: '多选项'
  }
  return typeMap[type] || '未知类型'
}

// 关闭组件
function closeModal() {
  visible.value = false
  emit('close')
}

</script>

<template>
  <NModal
    v-model:show="visible"
    preset="card"
    title="问卷管理"
    style="width: 95%; max-width: 1200px;"
    :mask-closable="false"
    @close="closeModal"
  >
    <!-- 问卷填写 -->
        <div style="max-height: 70vh; overflow-y: auto;">
          <NSpin :show="loading">
            <!-- 问卷选择 -->
            <NCard v-if="surveyList.length > 1" title="选择问卷" style="margin-bottom: 20px;">
              <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                <NButton
                  v-for="(survey, index) in surveyList"
                  :key="survey.id"
                  :type="currentSurveyIndex === index ? 'primary' : 'default'"
                  @click="switchSurvey(index)"
                >
                  {{ survey.name }}
                </NButton>
              </div>
            </NCard>

            <!-- 问卷内容 -->
            <div v-if="surveyData.info && surveyData.info.length > 0">
              <!-- 问卷标项 -->
              <NCard style="margin-bottom: 20px;">
                <h2 style="margin: 0 0 10px 0;">{{ surveyData.name }}</h2>
              </NCard>
              
              <!-- 项目列表 -->
              <NCard>
                <NForm>
                  <div v-for="(question, questionIndex) in surveyData.info" :key="question.id" 
                       style="margin-bottom: 30px;">
                    
                    <!-- 项目标项 -->
                    <div style="margin-bottom: 15px;">
                      <h4 style="margin: 0; display: inline;">
                        {{ questionIndex + 1 }}：{{ question.title }}
                      </h4>
                      <span v-if="question.required" style="color: red; margin-left: 5px;">*</span>
                      <span style="color: #999; font-size: 12px; margin-left: 10px;">
                        ({{ getQuestionTypeText(question.type) }})
                      </span>
                    </div>
                    
                    <!-- 填空项 -->
                    <NFormItem v-if="question.type == 1">
                      <NInput
                        type="textarea"
                        v-model:value="answers[questionIndex]"
                        placeholder="请输入您的答案"
                        :rows="3"
                        :maxlength="500"
                        show-count
                      />
                    </NFormItem>
                    
                    <!-- 单选项 -->
                    <NFormItem v-else-if="question.type == 2">
                      <NRadioGroup v-model:value="answers[questionIndex]">
                        <div v-for="(option, optionIndex) in question.options" :key="optionIndex" 
                             style="margin-bottom: 8px;">
                          <NRadio :value="optionIndex" :label="option.text" />
                        </div>
                      </NRadioGroup>
                    </NFormItem>
                    
                    <!-- 多选项 -->
                    <NFormItem v-else-if="question.type == 3">
                      <NCheckboxGroup v-model:value="answers[questionIndex]">
                        <div v-for="(option, optionIndex) in question.options" :key="optionIndex" 
                             style="margin-bottom: 8px;">
                          <NCheckbox :value="optionIndex" :label="option.text" />
                        </div>
                      </NCheckboxGroup>
                    </NFormItem>
                    <NDivider v-if="questionIndex < surveyData.info.length - 1" />
                  </div>
                </NForm>
              </NCard>
            </div>

            <!-- 无数据 -->
            <NEmpty v-else description="暂无问卷数据" />
          </NSpin>
        </div>

    <!-- 底部操作按钮 -->
    <template #footer>
      <div style="display: flex; justify-content: space-between;">
        <NButton @click="closeModal">关闭</NButton>
        <NButton 
          type="primary" 
          :loading="submitting"
          @click="submitSurvey"
          :disabled="!surveyData.info || surveyData.info.length === 0"
        >
          {{ submitting ? '提交中...' : '提交问卷' }}
        </NButton>
      </div>
    </template>
  </NModal>
</template>
